<?php
/**
 * CDbCommand 扩展类，
 * 重写 getConnection 方法，用以配置主从库选择，减少主数据库连接次数
 */
 
class CDbCommandExt extends CDbCommand {

	public function getConnection() {
		$conn = parent::getConnection();
		
		if(
			!CDbManager::isMaster() && 
			self::isReadOperation($this->getText()) &&
			$conn->enableSlave &&
			!$conn->getCurrentTransaction()
		) {
			$conn = $conn->slave;
		}
		
		$conn->active();
		return $conn;
	}
	
	/**
	 * 从sql语句判断是否为读取操作
	 * @return Boolean
	 */
	public static function isReadOperation($sql) {
		return preg_match("#^(SELECT|SHOW|DESCRIBE|PRAGMA)#i", ltrim($sql));
	}
}